<?php

class TopicModel extends MY_Model{
    public $table = 't_topic';
    public function __construct(){
        parent::__construct();
    }

    /**
     * 取出所有的二级话题列表
     * name: getTopicList
     * @return array
     * @throws Exception
     * @Author:taiyang
     */
    public function getTopicList($like='',$parent_id=''){
        $sql="select id,title from ".$this->table." where 1 and level=2 and status=1 ";
        $parent_id=intval($parent_id);
        if(!empty($parent_id)){
            $sql.=" and parent_id = ".$parent_id." ";
        }if(!empty($like)){
            $sql.=" and title like '%".$like."%' ";
        }
        $sql.=" order by id asc ";
        return $this->query_sql_list($sql);
    }

    /**
     * 取出分类
     * name: getTopicOne
     * @return array
     * @throws Exception
     * @Author:taiyang
     */
    public function getTopicOne(){
        $sql="select id,title from ".$this->table." where 1 and level=1";
        $res= $this->query_sql_list($sql);
        $list=array();
        foreach ($res as $val){
            $list[$val['id']]=$val['title'];
        }
        return $list;
    }

    /**
     * 分页列表
     * @param array $where
     * @param int $page
     * @param int $pagesize
     * @param array $orderBy
     * @return mixed
     */
    public function get_list($where = array(), $page = 1, $pagesize = 20, $orderBy = array()){
        $sql="select * from ".$this->table." where 1 and level=2 ";
        $sql.=$this->getWhereSql($where);
        $index = $page - 1 < 0 ? 0 : ($page - 1) * $pagesize;
        if(!empty($orderBy)){
            $sql.=" order by ".$orderBy[0]." ".$orderBy[1]." ";
        }
        $sql.=" limit ".$index.",".$pagesize."";
        return $this->query_sql_list($sql);
    }

    /**
     * 分页列表数量
     * @param array $where
     * @return mixed
     */
    public function get_list_num($where = array()){
        $sql="select count(*) from ".$this->table." where 1 and level=2 ";
        $sql.=$this->getWhereSql($where);
        return $this->query_sql_count($sql);
    }

    /**
     * 生成where条件
     * name: getWhereSql
     * @param array $where
     * @return string
     * @Author:taiyang
     */
    public function getWhereSql($where=array()){
        $sql='';
        if(!empty($where['category_id'])){
            $sql.=" and parent_id=".$where['category_id']." ";
        }
        if(!empty($where['s_num'])){
            $s_num_arr=explode('-',$where['s_num']);
            if(!empty($s_num_arr[1])){
                $sql.=" and post_num > ".$s_num_arr[0]." and post_num < ".$s_num_arr[1]." ";
            }
        }
        if(!empty($where['s_title'])){
            $sql.=" and title like '%".$where['s_title']."%' ";
        }
        if(!empty($where['is_hide'])){
            $sql.=" and status=".$where['is_hide']." ";
        }
        if(isset($where['is_hot'])){
            $sql.=" and is_hot=".$where['is_hot']." ";
        }
        return $sql;
    }
}